package com.xzcedu.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 徐州城
 * @version 1.0
 * 文件上传的服务端
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {

        //1. 服务端在本地 监听8888 端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端在8888端口 监听...");
        //2. 等待连接
        Socket socket = serverSocket.accept();

        //3. 读取客户端发送的数据
        //通过socket得到输入流
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //4. 将得到的 bytes[]，写入指定的路径，就得到一个文件
        String destFilePath = "src\\qie.jpg";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bos.write(bytes);//写入到文件中
        bos.close();

        //5. 发送信息给客户端
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("收到图片".getBytes());
        socket.shutdownOutput();//结束标记

        //关闭其他流
        bis.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}
